package utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import utils.StringUtils.MyStringBuffer;
import domain.Guy;

public class ObjectUtils {

	/**
	 * will build a json string, like ({"name":"Mike",...}) just simple class
	 * field
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJSONObject(Object obj) {
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
		msb.put("(");
		msb.put(getJSONObject_(obj));
		msb.put(")");
		
		
		return msb.getStringAndClose();
	}
	
	
	
	
	private static String getJSONObject_(Object obj) {
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();

		msb.put("{");

		boolean isHave = false;
		for (Method md : obj.getClass().getMethods()) {
			String mdName = md.getName();

			if (mdName.startsWith("get") && md.getParameterTypes().length == 0) {
				String fdName = mdName.replace("get", "");
				fdName = initialLowerCase(fdName);
				Object value = "null";
				try {
					value = md.invoke(obj, new Object[] {});
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				// build this field
				if (isHave)
					msb.put(",");
				msb.put("\"").put(fdName).put("\"");
				msb.put(":");
				msb.put("\"").put(value).put("\"");
				isHave = true;
			}
		}

		msb.put("}");

		return msb.getStringAndClose();
	}

	public static String getJSONList(Iterable<? extends Object> list) {
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
		msb.put("([");
		boolean isHave = false;
		for(Object obj : list){
			if(isHave) msb.put(",");
			msb.put(getJSONObject_(obj));
			isHave=true;
		}
		
		msb.put("])");

		return msb.getStringAndClose();
	}

	public static String initialLowerCase(String str) {
		char[] array = str.toCharArray();
		char f = array[0];
		if (f < 'a') {
			array[0] = (char) (f + 32);
		}
		return new String(array);
	}

	public static void main(String[] args) {
		Guy mike = new Guy();
		mike.setName("Mike");
		
		Guy john = new Guy();
		john.setName("John");
		
		List<Guy> list = new ArrayList<Guy>();
		list.add(mike);
		list.add(john);

		System.out.println(getJSONObject(mike));
		System.out.println(getJSONObject(john));
		
		System.out.println(getJSONList(list));

	}
	
	
	
	
}
